<?php

namespace Admin\Controller;

use Common\Controller\AdminController;

class OrdersController extends AdminController {

    public function index() {
        $account_user_id = $_SESSION['account_user_id'];
        $where['shopaccountid'] = $account_user_id;
        $order_no = $_REQUEST['orderno'];
        $start_date = $_REQUEST['start'];
        $end_date = $_REQUEST['end'];
        $status = $_REQUEST['orderstatus'];
        $paytype = $_REQUEST['paytype'];
        $ordertype = $_REQUEST['ordertype'];
        if (isset($order_no) && !empty($order_no)) {
            $where['orderId'] = $order_no;
            $param['orderno'] = $order_no;
        }
        if (isset($start_date) && !empty($start_date) && isset($end_date) && !empty($end_date)) {
            $where['a.createDT'] = array("between", array($start_date . " 00:00:00", $end_date . " 23:59:59"));
            $param['start'] = $start_date;
            $param['end'] = $end_date;
        } else {
            $where['a.createDT'] = array("between", array(date("Y-m-d", time() - 3600 * 24 * 30) . " 00:00:00", date("Y-m-d") . " 23:59:59"));
        }
//        echo json_encode($where);die;
        if (!empty($status) && $status != 999) {
            $where['gorderstatus'] = $status == "a" ? 0 : $status;
            $param['orderstatus'] = $status;
        }
        if (!empty($paytype) && $paytype != 999) {
            $where['paytype'] = $paytype;
            $param['paytype'] = $paytype;
        }
        if (!empty($ordertype) && $ordertype != 999) {
            $where['ordertype'] = $ordertype == "a" ? 0 : $ordertype;
            $param['ordertype'] = $ordertype;
        }
        $ordersModel = new \Admin\Model\OrdersModel();
        $result = $ordersModel->getList($where, $param);
        $orderDetailModel = new \Admin\Model\OrderDetailModel();
        foreach ($result['list'] as $key => &$val) {
            if (empty($val['wx_time_end'])) {
                $val['wx_time_end'] = '-';
            }
            $val['price'] = $val['price'] / 100;
            $val['realpayprice'] = $val['realpayprice'] / 100;
            $val['gorderstatus'] = $this->getOrderStatus($val['gorderstatus']);
            $val['guserstatus'] = $this->getUserStatus($val['guserstatus']);

            $str = '';
            $detail = $orderDetailModel->getList(array('orderId' => $val['order_no']));
            foreach ($detail as $k => $v) {
                $str .= $v['ptitle'] . ' X' . $v['count'] . ';';
            }
            $val['product'] = $str;
        }
        $this->result = $result['list'];
        $this->page = $result['page'];
        if (IS_AJAX) {
            $this->ajaxReturn($this->fetch("Orders/list_ajax"));
        } else {

            $this->display("Orders/order-list");
        }
    }

    public function downExcel() {
        $account_user_id = $_SESSION['account_user_id'];
        $where['shopaccountid'] = $account_user_id;
        $order_no = $_REQUEST['orderno'];
        $start_date = $_REQUEST['start'];
        $end_date = $_REQUEST['end'];
        $status = $_REQUEST['orderstatus'];
        $paytype = $_REQUEST['paytype'];
        $ordertype = $_REQUEST['ordertype'];
        if (isset($order_no) && !empty($order_no)) {
            $where['orderId'] = $order_no;
            $param['orderno'] = $order_no;
        }
        if (isset($start_date) && !empty($start_date) && isset($end_date) && !empty($end_date)) {
            $where['a.createDT'] = array("between", array($start_date . " 00:00:00", $end_date . " 23:59:59"));
            $param['start'] = $start_date;
            $param['end'] = $end_date;
        } else {
            $where['a.createDT'] = array("between", array(date("Y-m-d", time() - 3600 * 24 * 30) . " 00:00:00", date("Y-m-d") . " 23:59:59"));
        }
        if (!empty($status) && $status != 999) {
            $where['gorderstatus'] = $status == "a" ? 0 : $status;
            $param['orderstatus'] = $status;
        }
        if (!empty($paytype) && $paytype != 999) {
            $where['paytype'] = $paytype;
            $param['paytype'] = $paytype;
        }
        if (!empty($ordertype) && $ordertype != 999) {
            $where['ordertype'] = $ordertype == "a" ? 0 : $ordertype;
            $param['ordertype'] = $ordertype;
        }
        $ordersModel = new \Admin\Model\OrdersModel();
        $result = $ordersModel->getListForExcel($where, $param);
        foreach ($result['list'] as $key => &$val) {
            if (empty($val['wx_time_end'])) {
                $val['wx_time_end'] = '-';
            }
            $val['gorderstatus'] = $this->getOrderStatus($val['gorderstatus']);
            $val['guserstatus'] = $this->getUserStatus($val['guserstatus']);
        }
        $orderDetailModel = new \Admin\Model\OrderDetailModel();

        foreach ($result['list'] as $key => &$val) {
            $str = '';
            $detail = $orderDetailModel->getList(array('orderId' => $val['order_no']));
            foreach ($detail as $k => $v) {
                $str .= $v['ptitle'] . ' X' . $v['count'] . ';';
            }
            $val['product'] = $str;
        }
        $next_table = "<table border='1' style='text-align:center;width: 50%;margin: 0 auto;'> <tr>
                                    <th>编号</th>
                                    <th>订单号</th>
                                    <th>用户</th>
                                    <th>应付金额</th>
                                    <th>实付金额</th>
                                    <th>创建时间</th>
                                    <th>取货时间</th>
                                    <th>支付类型</th>
                                    <th>支付状态</th>
                                    <th>取货状态</th>
                                    <th>订单类型</th>
                                    <th>支付时间</th>
                                    <th>餐品详细</th>
                                </tr>";
        foreach ($result['list'] as $key => $value) {
            $one = "<tr>";
            $one .= "<td>" . ($key + 1) . "</td>";
            $one .= "<td>" . $value['order_no'] . "</td>";
            $one .= "<td>" . $value['name'] . "</td>";
            $one .= "<td>" . $value['price'] / 100 . "</td>";
            $one .= "<td>" . $value['realpayprice'] / 100 . "</td>";
            $one .= "<td>" . $value['createdt'] . "</td>";
            $one .= "<td> T" . ($value['pickuptime']) . "</td>";
            if ($value['paytype'] == 1) {
                $one .= "<td>微信付款</td>";
            } else {
                $one .= "<td>支付宝付款</td>";
            }
            $one .= "<td>" . $value['gorderstatus'] . "</td>";
            $one .= "<td>" . $value['guserstatus'] . "</td>";
            if ($value['ordertype'] == 1) {
                $one .= "<td>线下订单</td>";
            } else {
                $one .= "<td>线上订单</td>";
            }
            $one .= "<td>" . $value['wx_time_end'] . "</td>";
            $one .= "<td>" . $value['product'] . "</td>";
            $one .= "</tr>";
            $next_table.=$one;
        }
        $next_table.="</table>";
        $filename = '订单';
        header("Content-type:application/octet-stream;charset=utf-8");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . $filename . ".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        ob_start();
        echo $next_table;
        ob_flush();
        exit;
    }

    public function printOrders() {
        $account_user_id = $_SESSION['account_user_id'];
        $orderId = $_POST['orderId'];
        $data['createdt'] = date("Y-m-d H:i:s");
        $data['orderid'] = $orderId;
        $data['CMDType'] = 'PrintReceipt';
        $data['ExpireDT'] = date("Y-m-d H:i:s", time() + 3600*2);
        $data['shopaccountid'] = $account_user_id;
        $data['isexcuted'] = FALSE;
        $tasksModel = new \Admin\Model\TasksModel();
        $result = $tasksModel->addData($data);
        if ($result) {
            $this->ajaxReturn(array('code' => 10000, 'msg' => '请求成功', 'data' => array()));
        } else {
            $this->ajaxReturn(array('code' => 10000, 'msg' => '请求错误', 'data' => array()));
        }
    }

// 人工下单
    public function artificialOrder() {
        $account_user_id = $_SESSION['account_user_id'];
        $param = $_POST['food'];
        $memo = $_POST['memo'];
        $orderId = "D" . date("ymdHis") . rand(1000, 9999);
        $productModel = new \Admin\Model\ProductsModel();
        $orderModel = new \Admin\Model\OrdersModel();
        $price = 0;
        if (empty($param)) {
            $this->ajaxReturn(array('code' => 10001, 'msg' => '请选择菜品'));
        }
        foreach ($param as $key => $val) {

            $product = $productModel->getFind(array('id' => $val['id']));
            $price+=$product['realprice'] * $val['count'];
            $datas[$key]['orderId'] = $orderId;
            $datas[$key]['price'] = $product['price'];
            $datas[$key]['realprice'] = $product['realprice'];
            $datas[$key]['count'] = $val['count'];
            $datas[$key]['productId'] = $val['id'];
            $datas[$key]['skuId'] = $val['id'];
            $datas[$key]['createDT'] = date("Y-m-d H:i:s");
            $datas[$key]['status'] = 1;
            $datas[$key]['memo'] = $memo;
            $datas[$key]['ptitle'] = $product['name'];
            $datas[$key]['skutitle'] = $product['name'];
            $datas[$key]['pimageuri'] = $product['cover'];
        }
        $data['orderId'] = $orderId;
        $data['createDT'] = date("Y-m-d H:i:s");
        $data['price'] = $price;
        $data['realpayprice'] = $price;
        $data['shopaccountid'] = $account_user_id;
        $data['gorderstatus'] = 0;
        $data['guserstatus'] = 0;
        $data['paytype'] = 3;
        $data['ordertype'] = 1;
        $data['updatedt'] = date("Y-m-d H:i:s");
        $data['memo'] = $memo;
// 查询商家订单数
        $cWhere['shopaccountid'] = $account_user_id;
        $cWhere['createDT'] = array('between', array(date('Y-m-d') . " 00:00:00", date("Y-m-d") . " 23:59:59"));
        $orderCount = $orderModel->getCount($cWhere);
        if ($orderCount == 0 || empty($orderCount)) {
            $data['ordernum'] = "0001";
        } else {
            $count = $orderCount + 1;
            if (strlen($count) >= 4) {
                $data['ordernum'] = $count;
            } else {
                for ($i = 0; $i < 4 - strlen($count); $i++) {
                    $ordernum .= "0";
                }
                $data['ordernum'] = $ordernum . $count;
            }
        }
        $orderDetailModel = new \Admin\Model\OrderDetailModel();
        $oRes = $orderModel->addData($data);
        $odRes = $orderDetailModel->addDataAll($datas);
        if ($oRes && $odRes) {
            $this->ajaxReturn(array('code' => 10000, 'msg' => '请求成功', 'data' => array('order_no' => $data['orderId'])));
        } else {
            $this->ajaxReturn(array('code' => 10001, 'msg' => '下单错误', 'data' => array()));
        }
    }

    public function artificial() {
        $this->display();
    }

// 条形码支付
    public function barCodePay() {
        $order_no = $_POST['order_no'];
        $orderModel = new \Admin\Model\OrdersModel();
        $order = $orderModel->getFind(array('orderId' => $order_no));

        $pay_type = $_POST['pay_type'];
        $bar_code = $_POST['bar_code'];
        switch ($pay_type) {
            case 1:
                $result = $this->wxBarCodePay($order_no, $order['realpayprice'], "早餐", $bar_code);
                $this->ajaxReturn($result);
                break;
            case 2:
                $result = $this->aliBarCodePay($order_no, $order['realpayprice'] / 100, "早餐", $bar_code);
                $this->ajaxReturn($result);
                break;
            case 3: // 现金支付 直接更新订单
                $orderModel = new \Admin\Model\OrdersModel();
                $where['orderId'] = $order_no;
                $orders = $orderModel->getFind($where);
                if ($orders['gorderstatus'] != 1) {
                    $data['paytype'] = 3;
                    $data['gorderstatus'] = 1;
                    $data['guserstatus'] = 5;

                    $orderModel->saveData($where, $data);
                    $this->printOrder($order_no);
                }

                $this->ajaxReturn(array('code' => 10000, 'msg' => '支付完成'));
                break;
        }
    }

// 查询支付订单
    public function searchOrderPay() {
        $order_no = $_POST['order_no'];
        $pay_type = $_POST['pay_type'];
        switch ($pay_type) {
            case 1:
                $result = $this->SearchWxPay($order_no);
                $this->ajaxReturn($result);
                break;
            case 2:
                $result = $this->SearchAliPay($order_no);
                $this->ajaxReturn($result);
                break;
        }
    }

    public function getOrderStatus($status) {
        switch ($status) {
            case 0 :
                return "未支付";
                break;
            case 1 :
                return "已支付";
                break;
            case 2 :
                return "退款中";
                break;
            case 3 :
                return "已退款";
                break;
            case 4 :
                return "已关闭";
                break;
            case 5 :
                return "已完成";
                break;
        }
    }

    public function getUserStatus($status) {
        switch ($status) {
            case 0 :
                return "待接单";
                break;
            case 1 :
                return "已接单";
                break;
            case 2 :
                return "制作中";
                break;
            case 3 :
                return "待入柜";
                break;
            case 4 :
                return "已入柜";
                break;
            case 5 :
                return "取货完成";
                break;
        }
    }

    public function wxBarCodePay($orderno = '', $price = 0, $body = "", $bar_code = 0) {
        Vendor('Wxpay.WxPay#Api');
        $input = new \WxPayMicroPay();
        $input->SetBody($body);
        $input->SetOut_trade_no($orderno);
        $input->SetTotal_fee($price);
        $input->SetAuth_code($bar_code);
        $order = \WxPayApi::micropay($input);
        if ($order['return_code'] == 'SUCCESS' && $order['result_code'] == 'SUCCESS') {
            $orderModel = new \Admin\Model\OrdersModel();
// 直接更新订单
            $where['orderId'] = $orderno;
            $orders = $orderModel->getFind($where);
            if ($orders['gorderstatus'] != 1) {
                $data['wx_transaction_id'] = $order['transaction_id'];
                $data['results'] = 1;
                $data['gorderstatus'] = 1;
                $data['guserstatus'] = 5;
                $data['wx_time_end'] = date("Y-m-d H:i:s");
                $data['paytype'] = 1;
                $data['realpayprice'] = $order['total_fee'];

                $orderModel->saveData($where, $data);
                $this->printOrder($orderno);
            }

            return array('code' => 10000, 'msg' => '支付成功', 'data' => array());
        } else {
            return array('code' => 10001, 'msg' => $order['err_code_des'], 'data' => array());
        }
    }

    public function SearchWxPay($orderno) {
        Vendor('Wxpay.WxPay#Api');
        $input = new \WxPayMicroPay();
        $input->SetOut_trade_no($orderno);
        $res = \WxPayApi::orderQuery($input);
        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS' && $res['trade_state'] == "SUCCESS") {
            $orderModel = new \Admin\Model\OrdersModel();
// 直接更新订单
            $where['orderId'] = $orderno;
            $orders = $orderModel->getFind($where);
            if ($orders['gorderstatus'] != 1) {
                $data['wx_transaction_id'] = $res['transaction_id'];
                $data['results'] = 1;
                $data['gorderstatus'] = 1;
                $data['guserstatus'] = 5;
                $data['wx_time_end'] = date("Y-m-d H:i:s");
                $data['paytype'] = 1;
                $data['realpayprice'] = $res['total_fee'];

                $orderModel->saveData($where, $data);
                $this->printOrder($orderno);
            }

            return array('code' => 10000, 'msg' => '支付成功', 'data' => array());
        } else {
            return array('code' => 10001, 'msg' => $res['err_code_des'], 'data' => array());
        }
    }

    public function aliBarCodePay($orderno = '', $price = 0, $body = "", $bar_code = 0) {
        Vendor('alipay.aop.AopClient');
        vendor('alipay.aop.request.AlipayTradePayRequest');
        $aliPayConfig = C("AliPayConfig");
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $aliPayConfig['AppId'];
        $aop->rsaPrivateKey = $aliPayConfig['PrivateKey'];
        $aop->alipayrsaPublicKey = $aliPayConfig['PublicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipayTradePayRequest();
        $data['out_trade_no'] = $orderno;
        $data['scene'] = 'bar_code';
        $data['auth_code'] = $bar_code;
        $data['subject'] = $body;
        $data['total_amount'] = $price;
        $dataJson = json_encode($data);
//        $this->ajaxReturn($data);
        $request->setBizContent($dataJson);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            $orderModel = new \Admin\Model\OrdersModel();
            $price = $result->$responseNode->total_amount;
            $where['orderId'] = $orderno;
            $orders = $orderModel->getFind($where);
            if ($orders['gorderstatus'] != 1) {
                $data['wx_transaction_id'] = $result->$responseNode->trade_no;
                $data['results'] = 1;
                $data['gorderstatus'] = 1;
                $data['guserstatus'] = 5;
                $data['wx_time_end'] = date("Y-m-d H:i:s");
                $data['paytype'] = 2;
                $data['realpayprice'] = $price * 100;
                $orderModel->saveData($where, $data);
                $this->printOrder($orderno);
            }

            return array('code' => 10000, 'msg' => '支付成功', 'data' => array());
        } else if ($resultCode == 10003) {
            return array('code' => 10001, 'msg' => '支付处理中', 'data' => array());
        } else {
            return array('code' => 10001, 'msg' => $result->$responseNode->sub_msg, 'data' => array());
        }
    }

    public function SearchAliPay($orderno) {
        Vendor('alipay.aop.AopClient');
        vendor('alipay.aop.request.AlipayTradeQueryRequest');
        $aliPayConfig = C("AliPayConfig");
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $aliPayConfig['AppId'];
        $aop->rsaPrivateKey = $aliPayConfig['PrivateKey'];
        $aop->alipayrsaPublicKey = $aliPayConfig['PublicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';

        $request = new \AlipayTradeQueryRequest();
        $data['out_trade_no'] = $orderno;
        $dataJson = json_encode($data);
        $request->setBizContent($dataJson);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            $orderModel = new \Admin\Model\OrdersModel();
            $price = $result->$responseNode->total_amount;
            $where['orderId'] = $orderno;
            $orders = $orderModel->getFind($where);
            if ($orders['gorderstatus'] != 1) {
                $data['wx_transaction_id'] = $result->$responseNode->trade_no;
                $data['results'] = 1;
                $data['gorderstatus'] = 1;
                $data['guserstatus'] = 5;
                $data['wx_time_end'] = date("Y-m-d H:i:s");
                $data['paytype'] = 1;
                $data['realpayprice'] = $price * 100;
                $orderModel->saveData($where, $data);
                $this->printOrder($orderno);
            }

            return array('code' => 10000, 'msg' => '支付成功', 'data' => array());
        } else if ($resultCode == 10003) {
            return array('code' => 10001, 'msg' => '支付处理中', 'data' => array());
        } else {
            return array('code' => 10001, 'msg' => $result->$responseNode->sub_msg, 'data' => array());
        }
    }

// 人工下单打印小票
    public function printOrder($orderno) {
        $taksModel = new \Admin\Model\TasksModel();
        $data['orderid'] = $orderno;
        $data['createdt'] = date("Y-m-d H:i:s");
        $data['ExpireDT'] = date("Y-m-d H:i:s", time() + 3600*2);
        $data['CMDType'] = "PrintReceipt";
        $data['isexcuted'] = FALSE;
        $data['shopaccountid'] = $_SESSION['account_user_id'];
        $result = $taksModel->addData($data);
        return $result;
    }

}
